import json
import re
from datetime import datetime

from flask import Flask
from flask import request
from flask_cors import CORS
import map_api.tencent_map_api as tencent_map_api
import file_util
app = Flask(__name__)

#接口key
key = 'WNMBZ-35V3W-P7FRB-3GABJ-XWTY3-AZF4C'


@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

@app.route("/get_name", methods=['GET','POST'])
def get_name():
    name = request.args.get('name', '')
    if request.method == 'GET' :
        return dict(method='GET', name=name)
    elif request.method == 'POST' :
        return dict(method='POST', name=name)

@app.route("/geocoder", methods=['GET','POST'])
def geocoder():
    address = request.args.get('address', '')
    params = {}
    if address is None or len(address) == 0 or (address.isspace()):
        raise 'address must be not empty'
    else:
        params['address'] = address
    return tencent_map_api.geocoder(params)

@app.route("/suggestion", methods=['GET','POST'])
def suggestion():
    keyword = request.args.get('keyword', '')
    region = request.args.get('region', '')
    region_fix = request.args.get('region_fix', '')
    location = request.args.get('location', '')
    get_subpois = request.args.get('get_subpois', '')
    filter = request.args.get('filter', '')
    address_format = request.args.get('address_format', '')
    page_index = request.args.get('page_index', '')
    page_size = request.args.get('page_size', '')
    params = {}
    if keyword == None or len(keyword) == 0 or (keyword.isspace()):
        raise 'keyword must be not empty'
    else:
        params['keyword'] = keyword
    if region != None and len(region) != 0 and (not region.isspace()):
        params['region'] = region
    if region_fix != None and len(region_fix) != 0 and (not region_fix.isspace()):
        params['region_fix'] = region_fix
    if location != None and len(location) != 0 and (not location.isspace()):
        params['location'] = location
    if get_subpois != None and len(get_subpois) != 0 and (not get_subpois.isspace()):
        params['get_subpois'] = get_subpois
    if filter != None and len(filter) != 0 and (not filter.isspace()):
        params['filter'] = filter
    if address_format != None and len(address_format) != 0 and (not address_format.isspace()):
        params['address_format'] = address_format
    if page_index != None and len(page_index) != 0 and (not page_index.isspace()):
        params['page_index'] = page_index
    if page_size != None and len(page_size) != 0 and (not page_size.isspace()):
        params['page_size'] = page_size
    return tencent_map_api.suggestion(params)

# 获取全部行政区划数据
@app.route("/district", methods=['GET','POST'])
def district():
    return tencent_map_api.district()


# 根据ID，获取其的子级行政区划
# 本接口支持获取 指定区县（三级）其下乡镇/街道（四级）列表
# 父级行政区划ID（adcode），缺省时返回一级行政区划，也就是省级
@app.route("/getchildren", methods=['GET','POST'])
def getchildren():
    id = request.args.get('id', '')
    params = {}
    if params['id'] is not None and len(params['id']) != 0 and (not params['id'].isspace()):
        params['id'] = id
    return tencent_map_api.getchildren(params)


# search接口：搜索关键词为xxx的行政区划
# 搜索关键词： 1.支持输入一个文本关键词 2.支持多个行政区划代码(adcode)，英文逗号分隔
@app.route("/search", methods=['GET','POST'])
def search():
    keyword = request.form.get('keyword', '')
    params = {}
    if keyword is None or len(keyword) == 0 or (keyword.isspace()):
        raise 'keyword must be not empty'
    else:
        params['keyword'] = keyword
    return tencent_map_api.search(params)


@app.route("/get_sms", methods=['GET','POST'])
def get_sms():
    '''
    http://192.168.159.151:55000/get_sms?sms={sms}
    http://192.168.159.151:55000/get_sms?sms=验证码626323，短信接收时间：2024-09-20 09:40:00

    :return:
    '''
    sms = request.args.get('sms', '')
    print(f'收到转发短信[{datetime.now()}]sms:{sms}')
    if sms and sms[7:]:

        # 短信码头 写法
        # sms = sms[7:].replace('=', ':')
        # try:
        #     sms_json = json.loads(sms)
        # except Exception as e:
        #     print(f'===>>> error:{e}')
        #     sms_json={}
        # sms_code = re.findall('验证码(.+?)，', sms_json['smsBody'])
        # sms_date = sms_json['date']
        # if sms_code and sms_date:
        #     sms_json['sms_code'] = sms_code
        #     sms_json['sms_date'] = sms_date
        #     with open('F:\ideaWorkspace\miracleProject\miracle-python\yuanshentiyu\data\sms.json', 'w', encoding='utf-8') as file:
        #         json.dump(sms_json, file,  indent=2, ensure_ascii=False)
        # else:
        #     print('===>>> 无有效信息')

        # smsForworarder转发格式
        sms_code = re.findall('验证码(.+?)，', sms)
        sms_date = re.findall('\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', sms)
        print(f'sms_code:{sms_code} | sms_date:{sms_date}')
        sms_path = '../super-toolbox/resources/data/sms.json'
        file_util.create_not_exist(sms_path, True)
        if sms_code and sms_date:
            with open(sms_path, 'w', encoding='utf-8') as file:
                json.dump({'sms_code': sms_code[0], 'sms_date': sms_date[0], 'sms' : sms}, file,  indent=2, ensure_ascii=False)
        else:
            print('===>>> 无有效信息')

    else:
        print('===>>> 验证短信为空')
    return sms




# r'/*' 是通配符，让本服务器所有的 URL 都允许跨域请求
CORS(app, resources=r'/*')
# venv\Scripts\activate
# set FLASK_APP=hello #文件名是其他时候，跟具需要更改
# flask run
if __name__ == '__main__':
    # 指定port, 运行app
    # 0.0.0.0代表任何能代表这台机器的地址都可以访问
    app.run(debug=True,host='0.0.0.0', port='55000')